﻿using System;
using System.Linq;
using System.Threading;
using VideoSeller.Business.Data;
using VideoSeller.Business.Data.Enums;

namespace VideoSeller.Business.Models
{
	public class ContentModel : Repository<Content>
	{
		public Content GetContent(int id)
		{
			return Table.SingleOrDefault(x => x.Id == id);
		}

		public ContentLocalization GetContentLocalization(int id)
		{
			var content = Table.SingleOrDefault(x => x.Id == id);

			if (content != null)
			{
				var result = content.ContentLocalizations.SingleOrDefault(x => x.CultureName == Thread.CurrentThread.CurrentCulture.Name);
				return result ?? content.ContentLocalizations.SingleOrDefault(x => x.CultureName == "en-US");
			}

			return null;
		}

		public ContentLocalization GetBlock(string name)
		{
			var content = Table.SingleOrDefault(x => x.ContentPlace.KeyName == ContentPlaceType.Block.ToString() && x.ContentPlace.Name.ToLower() == name.ToLower());

			if (content != null)
			{
				var result = content.ContentLocalizations.SingleOrDefault(x => x.CultureName == Thread.CurrentThread.CurrentCulture.Name);
				return result ?? content.ContentLocalizations.SingleOrDefault(x => x.CultureName == "en-US");
			}

			return null;
		}

		public void SaveContent(Content content)
		{
			var value = GetContent(content.Id);

			if (value == null)
			{
				content.CreateDate = DateTime.Now;
				Insert(content);
			}
			else
			{
				value.ContentPlace.Name = content.ContentPlace.Name;
				value.ContentPlace.KeyName = content.ContentPlace.KeyName;
				for (var i = 0; i < content.ContentLocalizations.Count; i++)
				{
					var loc = value.ContentLocalizations.First(x => x.CultureName == content.ContentLocalizations[i].CultureName);
					loc.Title = content.ContentLocalizations[i].Title;
					loc.Description = content.ContentLocalizations[i].Description;
					loc.MetaDescription = content.ContentLocalizations[i].MetaDescription;
					loc.MetaKeywords = content.ContentLocalizations[i].MetaKeywords;
					loc.Body = content.ContentLocalizations[i].Body;
				}
			}

			SubmitAllChanges();
		}

		public void DeleteContent(int id)
		{
			var content = GetContent(id);

			if (content != null)
			{
				Delete(content);
			}
		}
	}
}